package com.wanglibao.woodtrade.woodtrade.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.flyco.dialog.listener.OnOperItemClickL;
import com.flyco.dialog.widget.ActionSheetDialog;
import com.google.gson.Gson;
import com.wanglibao.woodtrade.woodtrade.R;
import com.wanglibao.woodtrade.woodtrade.config.NetConfig;
import com.wanglibao.woodtrade.woodtrade.entity.ResponseEntity;
import com.wanglibao.woodtrade.woodtrade.entity.ResponseFileAndUrl;
import com.wanglibao.woodtrade.woodtrade.entity.ResponsePictrueNameEntity;
import com.wanglibao.woodtrade.woodtrade.entity.ShopEntity;
import com.wanglibao.woodtrade.woodtrade.jsonrpc.JsonRPCAsyncTask;
import com.wanglibao.woodtrade.woodtrade.model.User;
import com.wanglibao.woodtrade.woodtrade.model.impl.UserImpl;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.HomeFragmentRecommendAdapter;
import com.wanglibao.woodtrade.woodtrade.ui.fragment.adapter.model.Commodity;
import com.wanglibao.woodtrade.woodtrade.util.ConserveImage;
import com.wanglibao.woodtrade.woodtrade.util.GetPicPath;
import com.wanglibao.woodtrade.woodtrade.util.ToastUtil;
import com.wanglibao.woodtrade.woodtrade.widget.SVListView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/*
 *  我的店铺可以进行编辑
 */
public class MyShopActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    @Bind(R.id.rl_common_title)
    RelativeLayout rlCommonTitle;

    @Bind(R.id.vp_activity_shop_imglist)
    ViewPager vpActivityShopImglist;

    @Bind(R.id.sdv_activity_shop_icon)
    ImageView sdv_activity_shop_icon;

    @Bind(R.id.tv_activity_shop_name)
    TextView tvActivityShopName;

    @Bind(R.id.tv_activity_shop_com_info)
    TextView tvActivityShopComInfo;

    @Bind(R.id.sv_activity_my_shop)
    ScrollView sv_activity_my_shop;

    @Bind(R.id.list_activity_shop_commoditylist)
    SVListView listActivityShopCommoditylist;

    @Bind(R.id.tv_activity_shop_dot)
    TextView tvActivityShopDot;
    //===============================
    /* 请求码*/
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    public static final int EXTERNAL_STORAGE_REQ_CODE = 10;
    @Bind(R.id.tv_hot_shop_activity)
    TextView mTvHotShopActivity;
    /*记录选中viewpager的位置*/
    private int currrentPostion;
    /*一个bitmap 对象*/
    Bitmap bitMap;
    boolean isScrolled = false;
    /*高清图片的文件目录*/
    String cameraPath;
    /*转化时间格式*/
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    /*生成压缩图片的文件目录*/
    String desName = Environment.getExternalStorageDirectory() + "/wood/shop/";
    String fileName;
    MyVpAdapter myVpAdapter;
    /*CustomDialog*/
    ActionSheetDialog dialog;
    /*标示 是否是最后一页*/
    int Index;
    /*上传图片存放的集合*/
    List<String> upLoadShopPictrue = new ArrayList<>();
    /*图片的名称*/
    private String IMAGE_FILE_NAME;
    /*从服务器返回图片的名称*/
    String PicName = null;
    /*存放上传成功后，返回json中的fileName*/
    ResponsePictrueNameEntity mNameEntity = null;
    /*user中存放用户所有信息*/
    User user;
    public static final int TYPE_STROE = 2;
    /*存放token的实体类*/
    ResponseEntity mResponseEntity = null;
    /*临时生成的token*/
    String token = null;
    boolean isFrist = false;

    ShopEntity shopEntity;
    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.arg2 != 2) {
                System.out.println("=========================================");
                System.out.println(msg.obj.toString());
                System.out.println("+++++++++++++++++++++++++++++++++++++++++");
                if (msg.arg1 == NetConfig.TaskId.storeDetail) {
                    shopEntity = new Gson().fromJson(msg.obj.toString(), ShopEntity.class);
                    if (shopEntity.getImg_url().size() != 0) {
                        for (String picpictrueUrl : shopEntity.getImg_url()) {
                            upLoadShopPictrue.add(SubString(picpictrueUrl));
                        }
                    }
                    showView();
                }
                if (msg.arg1 == NetConfig.TaskId.imgUpload) {
                    MyShopActivity.this.finish();
                }
            }
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_shop);
        ButterKnife.bind(this);
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            rl_common_title.setPadding(0, 0, 0, 0);
        }
        initData();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) {
            return;
        } else {
            if (requestCode == CAMERA_REQUEST_CODE) {
                File file = ConserveImage.compressImage(cameraPath, desName, fileName, Bitmap.CompressFormat.JPEG, 100);
                Uri uri = Uri.fromFile(file);
                upLoadPictrue(file);
                if (Index == 0) {
                    myVpAdapter.addData(0, String.valueOf(uri));
                    vpActivityShopImglist.setAdapter(myVpAdapter);
                    tvActivityShopDot.setText(1 + "/" + 4);
                } else {
                    myVpAdapter.addData(currrentPostion, String.valueOf(uri));
                    vpActivityShopImglist.setAdapter(myVpAdapter);
                    vpActivityShopImglist.setCurrentItem(currrentPostion);
                    tvActivityShopDot.setText((currrentPostion + 1) + "/" + 4);
                }

            }
            if (requestCode == IMAGE_REQUEST_CODE) {
                Uri uri = data.getData();
                String string = uri.getPath();
                String path;
                if (Build.VERSION_CODES.KITKAT >= 19) {  // 或者 android.os.Build.VERSION_CODES.KITKAT这个常量的值是19
                    path = new GetPicPath().getPath_above19(MyShopActivity.this, uri);
                    System.out.println("path_above19:" + path);
                } else {
                    path = getFilePath_below19(uri);

                }
                File file1 = ConserveImage.compressImage(path, desName, fileName, Bitmap.CompressFormat.JPEG, 100);
                Uri uri1 = Uri.fromFile(file1);
                upLoadPictrue(file1);
                if (Index == 0) {
                    myVpAdapter.addData(0, String.valueOf(uri1));
                    vpActivityShopImglist.setAdapter(myVpAdapter);
                    tvActivityShopDot.setText(1 + "/" + 4);
                } else {
                    myVpAdapter.addData(currrentPostion, String.valueOf(uri1));
                    vpActivityShopImglist.setAdapter(myVpAdapter);
                    vpActivityShopImglist.setCurrentItem(currrentPostion);
                    tvActivityShopDot.setText((currrentPostion + 1) + "/" + 4);
                }

            }
        }
    }

    /*请求权限*/
    public void requestPermission() {
        //判断当前Activity是否已经获得了该权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            //如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "please give me the permission", Toast.LENGTH_SHORT).show();
            } else {
                //进行权限请求
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_REQ_CODE);
            }
        } else {
        }
    }

    /**
     * API19以下获取图片路径的方法
     *
     * @param uri
     */
    private String getFilePath_below19(Uri uri) {
        //这里开始的第二部分，获取图片的路径：低版本的是没问题的，但是sdk>19会获取不到
        String[] proj = {MediaStore.Images.Media.DATA};
        //好像是android多媒体数据库的封装接口，具体的看Android文档
        Cursor cursor = getContentResolver().query(uri, proj, null, null, null);
        //获得用户选择的图片的索引值
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        System.out.println("***************" + column_index);
        //将光标移至开头 ，这个很重要，不小心很容易引起越界
        cursor.moveToFirst();
        //最后根据索引值获取图片路径   结果类似：/mnt/sdcard/DCIM/Camera/IMG_20151124_013332.jpg
        String path = cursor.getString(column_index);
        System.out.println("path:" + path);
        return path;
    }

    /**
     * @param file 上传的图片
     */
    public void upLoadPictrue(final File file) {
        if (token != null) {
            OkHttpUtils.post()
                    .addParams("token", token)
                    .addFile("filename", IMAGE_FILE_NAME, file)
                    .url(NetConfig.PICTRUE_UPLOAD_URL)
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e) {
                        }

                        @Override
                        public void onResponse(String response) {
//                            System.out.println("response:" + response);
                            mNameEntity = new Gson().fromJson(response, ResponsePictrueNameEntity.class);
                            ResponseFileAndUrl fileAndUrl = new Gson().fromJson(mNameEntity.getErr_msg().toString(), ResponseFileAndUrl.class);
                            upLoadShopPictrue.add(fileAndUrl.getFilename().getName());
                        }
                    });
        }
    }

    /*
    *  截取字符串
    * */
    public String SubString(String pictrueUrl) {
        String string = pictrueUrl;
        int i = string.indexOf("file=");
        int i1 = string.lastIndexOf("&");
        String s = string.substring(i + 5, i1);
        return s;
    }

    private void initData() {
        tvTitle.setText("我的店铺");
        addViewClicklistener(tvBack);
        user = new UserImpl(this).getUser();
        String id = new UserImpl(this).getUser().store_id;
        JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_STORE,
                NetConfig.storeDetail, handler, "jsonObject", NetConfig.TaskId.storeDetail, new Object[]{id});
        jsonRPCAsyncTask.execute(new Void[]{});
    }

    /*
    * 获取数据后，将数据展示在View上
    * */
    public void showView() {
        tvActivityShopName.setText(shopEntity.getCompany());
        //添加热度字段
        mTvHotShopActivity.setText("热度："+shopEntity.getStore_hot());
        ImageOptions imageOptions = new ImageOptions.Builder().setLoadingDrawable(getResources().getDrawable(R.mipmap.ic_lose_p_loading))
                .setFailureDrawable(getResources().getDrawable(R.mipmap.ic_lose_p_fail)).
                        setCircular(true).build();
        x.image().bind(sdv_activity_shop_icon, shopEntity.getLogo_img_url(), imageOptions);
        tvActivityShopComInfo.setText(shopEntity.getCom_info());

//        shopEntity.getImg_url().add("http://pic.sucaibar.com/pic/201307/04/4deb850c0d.png");
        myVpAdapter = new MyVpAdapter();
        vpActivityShopImglist.setAdapter(myVpAdapter);
        vpActivityShopImglist.addOnPageChangeListener(new MyOnPageChangeListener());

        Commodity commodity = new Commodity();
        commodity.setList(shopEntity.getGoodslist());
        HomeFragmentRecommendAdapter homeFragmentRecommendAdapter = new HomeFragmentRecommendAdapter(this, commodity);
        listActivityShopCommoditylist.setAdapter(homeFragmentRecommendAdapter);
        listActivityShopCommoditylist.setOnItemClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        sv_activity_my_shop.smoothScrollTo(0, 0);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imgbtn_commonTitle_back:
                NetWorking();
                break;

            default:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        NetWorking();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(this, CommodityActivity.class);
        intent.putExtra("id", shopEntity.getGoodslist().get(position).getGoods_id());
        startActivity(intent);
    }

    /*获取token*/
    public void getToken() {
        OkHttpUtils.post().addParams("access_key", NetConfig.ACCESS_KEY)
                .addParams("secret_key", NetConfig.SECRET_KEY)
                .url(NetConfig.ACHIEVE_TOKEN_URL)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                    }

                    @Override
                    public void onResponse(String response) {
                        mResponseEntity = new Gson().fromJson(response, ResponseEntity.class);
                        token = mResponseEntity.getToken();
                    }
                });
    }

    public void NetWorking() {
        StringBuffer stringBuffer = new StringBuffer();
        for (String pictrueName : upLoadShopPictrue) {
            if ("".equals(pictrueName.toString().trim())) {

            } else {
                stringBuffer.append(pictrueName).append(",");
            }

        }
        String string = TextUtils.isEmpty(stringBuffer.toString()) ? "" : stringBuffer.toString().substring(0, stringBuffer.length() - 1);
        if ("".equals(string)) {
            if (!isFrist) {
                finish();
            } else {
                JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_COMMON,
                        NetConfig.imgUpload, handler,
                        "jsonObject", NetConfig.TaskId.imgUpload, new Object[]{user.store_id, TYPE_STROE, string, user.token});
                jsonRPCAsyncTask.execute(new Void[]{});
            }

        } else {
            JsonRPCAsyncTask jsonRPCAsyncTask = new JsonRPCAsyncTask(this, NetConfig.SERVER + NetConfig.TYPE_COMMON,
                    NetConfig.imgUpload, handler,
                    "jsonObject", NetConfig.TaskId.imgUpload, new Object[]{user.store_id, TYPE_STROE, string, user.token});
            jsonRPCAsyncTask.execute(new Void[]{});
        }

    }

    /*
    * 弹出个customDialog  拍照、选择本地相册
    * */
    private void ActionSheetDialogNoTitle() {
        final String[] stringItems = {"拍照", "选择本地相册"};
        dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        requestPermission();
                        SelectPictrueFromCamera();
                        break;
                    case 1:
                        requestPermission();
                        SelectPictrueFromSdCard();
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /*
    * 弹出个customDialog  拍照、选择本地相册、删除
    * */
    private void ActionSheetDialogNoTitle1() {
        final String[] stringItems = {"拍照", "选择本地相册", "删除"};
        dialog = new ActionSheetDialog(this, stringItems, null);
        dialog.isTitleShow(false).show();
        dialog.setOnOperItemClickL(new OnOperItemClickL() {
            @Override
            public void onOperItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position) {
                    case 0:
                        requestPermission();
                        SelectPictrueFromCamera();
                        myVpAdapter.remove(currrentPostion);
                        upLoadShopPictrue.remove(currrentPostion);
                        break;
                    case 1:
                        requestPermission();
                        SelectPictrueFromSdCard();
                        myVpAdapter.remove(currrentPostion);
                        upLoadShopPictrue.remove(currrentPostion);
                        break;
                    case 2:
                        dialog.dismiss();
                        isFrist = true;
                        myVpAdapter.remove(currrentPostion);
                        upLoadShopPictrue.remove(currrentPostion);
                        if (currrentPostion == 0) {
                            tvActivityShopDot.setText(1 + "/" + 4);
                        } else {
                            tvActivityShopDot.setText(currrentPostion + "/" + 4);
                        }
                        vpActivityShopImglist.setAdapter(myVpAdapter);
                        if (currrentPostion > 0) {
                            vpActivityShopImglist.setCurrentItem(currrentPostion - 1);
                        } else if (currrentPostion == 0) {
                            vpActivityShopImglist.setCurrentItem(currrentPostion);
                        }
                        break;
                    default:
                        break;
                }
            }
        });
    }

    /*
     * 选择照片 通过系统相机进行拍照
     */
    public void SelectPictrueFromCamera() {
        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            try {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory().getPath()
                        + "/wood/shop/");
                if (!file.exists()) file.mkdirs();
                //指定保存路径
                cameraPath = Environment.getExternalStorageDirectory().getPath()
                        + "/wood/shop/" + format.format(new Date()) + ".jpg";
                File imageFile = new File(cameraPath);
                Uri imageFileUri = Uri.fromFile(imageFile);
                intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri);
                startActivityForResult(intent, CAMERA_REQUEST_CODE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(MyShopActivity.this, "没有找到储存目录", Toast.LENGTH_LONG).show();
            }
        } else {
            Toast.makeText(MyShopActivity.this, "没有储存卡", Toast.LENGTH_LONG).show();
        }
        dialog.dismiss();
    }

    /* 选择照片 通过系统相册 从SdCard*/
    public void SelectPictrueFromSdCard() {
        Intent intentFromGallery = new Intent();
        intentFromGallery.setType("image/*"); // 设置文件类型    
        intentFromGallery.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intentFromGallery, IMAGE_REQUEST_CODE);
        dialog.dismiss();
    }

    class MyVpAdapter extends PagerAdapter {
        Drawable mDrawable = null;

        public MyVpAdapter() {
            mDrawable = MyShopActivity.this.getResources().getDrawable(R.mipmap.ic_edit_big_addphoto);
            shopEntity.getImg_url().add("");
        }

        @Override
        public int getCount() {
            if (shopEntity.getImg_url() != null) {
                if (shopEntity.getImg_url().size() > 4) {
                    return 4;
                }
                return shopEntity.getImg_url().size();
            } else {
                return 0;
            }
        }

        public void addData(int position, String string) {
            shopEntity.getImg_url().add(position, string);
            notifyDataSetChanged();
        }

        public void remove(int position) {
            shopEntity.getImg_url().remove(position);
            notifyDataSetChanged();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        // 销毁
        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        // 实例化每个viewpager 页面
        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            SimpleDraweeView sw = new SimpleDraweeView(MyShopActivity.this);
            if (shopEntity.getImg_url().size() == 0) {
                sw.setImageDrawable(mDrawable);
            } else {
                if (position == shopEntity.getImg_url().size() - 1) {
                    sw.setImageDrawable(mDrawable);
                } else {
                    sw.setImageURI(Uri.parse(shopEntity.getImg_url().get(position)));
                }
            }
            sw.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    currrentPostion = position;
                    getToken();
                    fileName = format.format(new Date()) + "compress" + ".jpg";
                    IMAGE_FILE_NAME = format.format(new Date()) + ".jpg";
                    if (shopEntity.getImg_url() != null) {
                        if (position == (shopEntity.getImg_url().size() - 1)) {
                            Index = 0;
                            ActionSheetDialogNoTitle();
                        } else {
                            Index = 1;
                            ActionSheetDialogNoTitle1();
                        }
                    } else {
                        ToastUtil.createNormalToast("集合中没有元素");
                    }
                }
            });
            container.addView(sw);
            return sw;
        }
    }

    /*viewpager的 监听*/
    class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            isScrolled = true;
        }

        @Override
        public void onPageSelected(int position) {
            tvActivityShopDot.setText((position + 1) + "/" + 4);
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }
}
